package com.lablzh.gdxy.controller;

import com.lablzh.gdxy.component.UserDetailsUtil;
import com.lablzh.gdxy.entity.Admin;

import com.lablzh.gdxy.entity.Instructor;
import com.lablzh.gdxy.entity.Student;

import com.lablzh.gdxy.entity.Teacher;
import com.lablzh.gdxy.entity.activity.Team;
import com.lablzh.gdxy.entity.design.Design;
import com.lablzh.gdxy.repository.StudentRepositoty;
import com.lablzh.gdxy.repository.TeacherRepository;
import com.lablzh.gdxy.service.InfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用于获取用户的个人信息
 * auth:lakshy
 */
@RestController
public class InfoController {
    @Autowired
    private TeacherRepository teacherRepository;

    @Autowired
    private InfoService infoService;

    @Autowired
    private StudentRepositoty studentRepositoty;

    @Autowired
    private UserDetailsUtil userDetailsUtil;

    @GetMapping("/getRole")
    public String getRole() {
        String userRole = userDetailsUtil.getUserRole();
        return userRole.substring(5, userRole.length());
    }

    /**
     * 多条件查询学生，姓名，学号，专业，班级
     */
    @PreAuthorize("hasAnyRole('admin', 'teacher')")
    @PostMapping("/queryStudent")
    public Map queryStudent(@RequestBody Student student, @RequestParam("page") Integer page) {
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("stID", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("major", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("classes", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<Student> example = Example.of(student, exampleMatcher);
        Pageable designPage = PageRequest.of(page - 1, 20, Sort.by(Sort.Direction.DESC, "id"));
        Page<Student> all = studentRepositoty.findAll(example, designPage);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("student", all.getContent());
        return data;
    }

    /**
     * 学生获取自己的个人资料
     *
     * @return
     */
    @PreAuthorize("hasRole('student')")
    @GetMapping("/studentInfo")
    public Student getStudentInfo() {
        return infoService.getStudentInfo();
    }

    /**
     * 教师获取自己的个人资料
     *
     * @return
     */
    @PreAuthorize("hasRole('teacher')")
    @GetMapping("/teacherInfo")
    public Teacher getTeacherInfo() {
        return infoService.getTeacherInfo();
    }

    /**
     * 管理员获取自己的个人资料
     *
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/adminInfo")
    public Admin getAdminInfo(HttpServletRequest request) {
        return infoService.getAdminInfo();
    }

    /**
     * 辅导员获取自己的个人资料
     *
     * @return
     */
    @PreAuthorize("hasRole('instructor')")
    @GetMapping("/instructorInfo")
    public Instructor getInstructorInfo() {


        return infoService.getInstructorInfo();

    }

    /**
     * 根据用户名获取管理员的个人资料
     *
     * @param username
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/adminInfoByUsername")
    public Admin getAdminInfoByUsername(@RequestParam("username") String username) {
        return infoService.getAdminInfoByUsername(username);
    }

    /**
     * 根据用户名获取学生的个人资料
     *
     * @param username
     * @return
     */
    @GetMapping("/studentInfoById")
    public Student getStudentInfoByUsername(@RequestParam("username") String username) {
        Student student = infoService.getStudentInfoByUsername(username);
        if (!userDetailsUtil.getUserRole().equals("ROLE_admin")) {
            student.setPassword("");
        }
        return student;
    }

    /**
     * 根据用户名获取教师的个人资料
     *
     * @param username
     * @return
     */
    @GetMapping("/teacherInfoById")
    public Teacher getTeacherInfoByUsername(@RequestParam("username") String username) {
        Teacher teacher = infoService.getTeacherInfoByUsername(username);
        if (!userDetailsUtil.getUserRole().equals("ROLE_admin")) {
            teacher.setPassword("");
        }
        return teacher;
    }

    /**
     * 根据用户名获取辅导员的个人资料
     *
     * @param username
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/instructorInfoById")
    public Instructor getInstructorInfoByUsername(@RequestParam("username") String username) {
        return infoService.getInstructorInfoByUsername(username);
    }

    /**
     * 修改学生个人资料
     *
     * @param student
     * @return
     */

    @PutMapping("/studentInfo")
    public String updateStudentInfo(@RequestBody Student student) {
        if (userDetailsUtil.getUserDetails().equals(student.getStID())) {
            return infoService.putStudentInfo(student);
        } else {
            return "你无权修改！";
        }

    }


    /**
     * 修改教师个人资料
     *
     * @param teacher
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher','admin')")
    @PutMapping("/teacherInfo")
    public String updateTeacherInfo(@RequestBody Teacher teacher) {
        return infoService.putTeacherInfo(teacher);
    }

    /**
     * 修改管理员个人资料
     *
     * @param admin
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @PutMapping("/adminInfo")
    public String updateAdminInfo(@RequestBody Admin admin) {
        return infoService.putAdminInfo(admin);
    }

    /**
     * 修改辅导员个人资料
     *
     * @param instructor
     * @return
     */
    @PreAuthorize("hasAnyRole('admin','instructor')")
    @PutMapping("/instructorInfo")
    public String updateInstructorInfo(@RequestBody Instructor instructor) {
        return infoService.putInstructorInfo(instructor);
    }

    /**
     * 获取所有的辅导员
     *
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/instructor")
    public List<Instructor> getAllInstructor() {
        return infoService.getAllInstructor();
    }

    /**
     * 获取所有的教师
     *
     * @return
     */
//    @PreAuthorize("hasAnyRole('admin','teacher')")
    @GetMapping("/teacher")
    public List<Teacher> getAllTeacher() {
        return infoService.getAllTeacher();
    }

    /**
     * 条件查询：查询条件有:姓名，学院，院系
     *
     * @param teacher
     * @param page
     * @return
     */
    @PreAuthorize("hasAnyRole('admin', 'teacher')")
    @PostMapping("/queryTeacher")
    public Map getQueryAllTeacher(@RequestBody(required = false) Teacher teacher,
                                  @RequestParam(name = "page", defaultValue = "0") Integer page) {
        System.out.println("teacher:" + teacher);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("college", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("department", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<Teacher> example = Example.of(teacher, exampleMatcher);
        Pageable designPage = PageRequest.of(page - 1, 20, Sort.by(Sort.Direction.DESC, "id"));
        Page<Teacher> all = teacherRepository.findAll(example, designPage);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("teacher", all.getContent());
        return data;
    }

    /**
     * 获取所有的管理员
     *
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/admin")
    public List<Admin> getAllAdmin() {
        return infoService.getAllAdmin();
    }

    /**
     * 获取所有的学生
     *
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/student")
    public List<Student> getAllStudent() {
        return infoService.getAllStudent();
    }

    @PreAuthorize("hasRole('admin')")
    @GetMapping("/studentpage")
    public Object getAllStudent1(@RequestParam("page") Integer pagenum) {
        Page<Student> page = infoService.querystudentSelective(pagenum, 20);
        //查询结果总行数
        System.out.println(page.getTotalElements());
        //按照当前分页大小，总页数
        System.out.println(page.getTotalPages());
        //按照当前页数、分页大小，查出的分页结果集合
       /* for (Goods goods: page.getContent()) {
            System.out.println(goods.toString());
        }*/
        System.out.println("-------------------------------------------");
        List<Student> student = page.getContent();
        Long total = page.getTotalElements();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("student", student);
        data.put("totalPage", page.getTotalPages());
        return data;
    }

}
